#include "fileviewer.h"
#include <cstdio>

FileViewer::FileViewer(QWidget *parent) : QWidget(parent) {
	ui.setupUi(this);
	doc=0;
	currentPage=-1;
	//connect(ui.tableWidget, SIGNAL(cellClicked(int, int)), this, SLOT(pageSelected(int, int)));
	ui.tableWidget->horizontalHeader()->hide();
	ui.tableWidget->verticalHeader()->hide();
}

FileViewer::~FileViewer() {
}

void FileViewer::setPage(int page) {
    if (page != currentPage) {
    	ui.tableWidget->scrollToItem(ui.tableWidget->item(page, 0));
    	emit showPage(page);
    }
}

void FileViewer::documentLoaded(Poppler::Document *doc) {
	this->doc=doc;
	int pcount=doc->numPages();

	int thnMaxWidth=165;
	int thnMaxHeight=230;

	ui.tableWidget->clear();
	ui.tableWidget->scroll(0, 0);
	ui.tableWidget->setRowCount(pcount);
	ui.tableWidget->setEnabled(true);
	ui.tableWidget->setColumnWidth(0, 200 );

	for (int i=0; i<pcount; i++) {
		Poppler::Page *page = doc->page(i);
		qreal ws=thnMaxWidth*0.72/page->pageSizeF().width();
		qreal hs=thnMaxHeight*0.72/page->pageSizeF().height();
		qreal scale=qMin(ws, hs);


		QImage image = page->renderToImage(scale * physicalDpiX(), scale * physicalDpiY());
		Page *pageImg=new Page();
		pageImg->setPixmap(QPixmap::fromImage(image));
		pageImg->setPageSize(image.size());
		pageImg->setPageNo(i);
		connect(pageImg, SIGNAL(pageSelected(int)), this,  SLOT(pageSelected(int)));
		connect(this, SIGNAL(showPage(int)), pageImg, SLOT(showPage(int)));
		ui.tableWidget->setItem(i, 0, new QTableWidgetItem(tr("%1").arg(i)));
		ui.tableWidget->setCellWidget(i, 0, pageImg);
		ui.tableWidget->setRowHeight(i, 230);
	}
}

void FileViewer::pageSelected(int page) {
	emit pageChanged(page);
}

